// pages/my/invoice/invoice.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs:[{name:'可开发票'},{name:'历史开票'}],
    page:1,
    dataList:[],
    currentTab:0,
    isAll: false,
    totalPrice: 0,
    buyNum: 0,
    cartIds:[]
  },
  filters: {
    getPrice(price) {
      price=parseFloat(price);
      price = price || 0;
      return price.toFixed(2);
    }
  },
  onShow(){
    if(this.data.currentTab==1){
      return;
    }
    this.change({detail:{index:0}});
  },
  buyChange(e) {
    this.setData({
      cartIds: e.detail.value
    })
    this.data.dataList.map(item => {
      if (this.data.cartIds.indexOf(item.id.toString())>=0) {
        item.selected = true;
      } else {
        item.selected = false;
      }
    })
    setTimeout(() => {
      this.calcHandle()
    }, 0)
  },
  calcHandle() {
    let buyNum = 0;
    let totalPrice = 0;
    let selectedNum = 0;
    this.data.dataList.map((item) => {
      if (item.selected) {
        buyNum += 1;
        totalPrice += parseFloat(item.price);
        selectedNum++;
      }
    })
    this.setData({
      isAll: selectedNum === this.data.dataList.length,
      buyNum: buyNum,
      totalPrice: totalPrice.toFixed(2)
    })
  },
  checkAll() {
    this.setData({
      isAll: !this.data.isAll,
      cartIds: []
    })
    let that=this;
    let buyNum = 0;
    let totalPrice = 0;
    let cartIds = [];
    this.data.dataList.map((item,index) => {
      let key="dataList["+index+"].selected";
      that.setData({
        [key]: that.data.isAll
      })
      if (that.data.isAll) {
        buyNum += 1;
        totalPrice += parseFloat(item.price);
        cartIds.push(item.id);
      }
    })
    this.setData({
      totalPrice: totalPrice.toFixed(2),
      cartIds: cartIds,
      buyNum: buyNum
    })
  },
  change(e){
    this.setData({
      currentTab: e.detail.index,
      page: 1,
      cartIds: [],
      buyNum: 0,
      totalPrice: 0,
      isAll: false,
      dataList: []
    })
    this.load();
  },
  getNow(){
    if(this.data.cartIds.length==0){
      wx.util.toast("请选择订单");
      return;
    }
    let ids=this.data.cartIds.join(",");
    wx.navigateTo({
      url:"/pages/my/invoice/get?ids="+ids
    })
  },
  async load(){
    let res=await wx.util.post("fp/index",{type:this.data.currentTab});
    this.setData({
      dataList:  res.data
    })
  },
  openPdf(e){
    let url=e.currentTarget.dataset.url;
    wx.showLoading({
      title: '加载中...'
    });
    wx.downloadFile({
      url: url,
      success: function (res) {
      wx.hideLoading();
        var filePath = res.tempFilePath;
        wx.openDocument({
          filePath: filePath,
          showMenu: true
        });
      }
    });
  }
})